package com.tengxing.e1.FactoryTest;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.PlaybackParams;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import java.util.Locale;

public class Speak_Test_Activity extends AppCompatActivity {
    private static final String TAG = "Speak_Test_Activity";
    SharedPreferences sharedPreferences;
    SharedPreferences.Editor editor;
    Button btn_Speaker_Play, btn_Change_Speaker, btn_Speak_Pass, btn_Speak_Fail;
    Context context;
    TextToSpeech textToSpeech;
    private MediaPlayer mediaPlayer;
    private AudioManager audioManager;
    int speaker_status = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_speak_test);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        sharedPreferences = getSharedPreferences("Test_Result", MODE_PRIVATE);
        audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        TTS_Init();
        Factory_Speak_BTN();
    }


    private void Factory_Speak_BTN(){
        btn_Speak_Pass = findViewById(R.id.btn_Speak_Pass);
        btn_Speak_Pass.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                editor = sharedPreferences.edit();
                editor = editor.putString("Speak", "通过");
                if (editor.commit()) {
                    Toast.makeText(Speak_Test_Activity.this, "测试结果保存成功", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(Speak_Test_Activity.this, MainActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    Toast.makeText(Speak_Test_Activity.this, "测试结果保存失败", Toast.LENGTH_SHORT).show();
                }
            }
        });

        btn_Speak_Fail = findViewById(R.id.btn_Speak_Fail);
        btn_Speak_Fail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                editor = sharedPreferences.edit();
                editor = editor.putString("Speak", "未通过");
                if (editor.commit()) {
                    Toast.makeText(Speak_Test_Activity.this, "测试结果保存成功", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(Speak_Test_Activity.this, MainActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    Toast.makeText(Speak_Test_Activity.this, "测试结果保存失败", Toast.LENGTH_SHORT).show();
                }
            }
        });

        btn_Speaker_Play = findViewById(R.id.btn_Speaker_Play);
        btn_Speaker_Play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TTS_Fun();
                //mediaPlayerSpeak();
            }
        });


        btn_Change_Speaker = findViewById(R.id.btn_Change_Speaker);
        btn_Change_Speaker.setText("扬声器切换（已关）");
        btn_Change_Speaker.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(speaker_status==0){
                    speaker_status=1;
                    audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);//MODE_IN_COMMUNICATION ok
                    audioManager.setSpeakerphoneOn(true);

                    btn_Change_Speaker.setText("扬声器切换（已开）");
                }else{
                    speaker_status=0;
                    audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
                    audioManager.setSpeakerphoneOn(false);

                    btn_Change_Speaker.setText("扬声器切换（已关）");
                }

            }
        });
    }

    private void mediaPlayerSpeak(){

        mediaPlayer = MediaPlayer.create(this, R.raw.e1_start_self_test);
        PlaybackParams playbackParams = mediaPlayer.getPlaybackParams();
        playbackParams.setSpeed((float)0.85);
        mediaPlayer.setPlaybackParams(playbackParams);


        mediaPlayer.start();
    }

    private void TTS_Init(){
        textToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {

            }
        });
    }
    private void TTS_Fun(){
        /*try {
            textToSpeech.setLanguage(Locale.ENGLISH);
            textToSpeech.speak("This is text to speech demo.", TextToSpeech.QUEUE_FLUSH, null, null);
        }catch (Exception e){
            Log.e(TAG, "SpeakClick:"+e);
        }*/

        try {
            textToSpeech.setLanguage(Locale.CHINESE);
            textToSpeech.speak("扬声器正在播放，如果有声音，请点通过测试", TextToSpeech.QUEUE_FLUSH, null, null);
        }catch (Exception e){
            Log.e(TAG, "SpeakClick:"+e);
        }

        Log.d(TAG, "EN:"+textToSpeech.isLanguageAvailable(Locale.US));
        Log.d(TAG, "EN:"+textToSpeech.isLanguageAvailable(Locale.ENGLISH));
        Log.d(TAG, "CN:"+textToSpeech.isLanguageAvailable(Locale.CHINA));
        Log.d(TAG, "CN:"+textToSpeech.isLanguageAvailable(Locale.CHINESE));
    }






    @Override
    public void onBackPressed() {
        if (textToSpeech != null) {
            textToSpeech.stop();
            textToSpeech.shutdown();
        }
        if(mediaPlayer != null){
            mediaPlayer.release();
            mediaPlayer=null;
        }
        Intent intent = new Intent(Speak_Test_Activity.this, MainActivity.class);
        startActivity(intent);
        finish();
        Toast.makeText(Speak_Test_Activity.this, "直接退出不会保存结果", Toast.LENGTH_SHORT).show();
        super.onBackPressed();
    }
}